package com.runshu.newsmartark.activity;

import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.adapter.NewProDtaAdapter;
import com.runshu.newsmartark.base.BaseActivity;
import com.runshu.newsmartark.common.ConstantUrl;
import com.runshu.newsmartark.entity.CategoryListEntity;
import com.runshu.newsmartark.entity.HwInfoUtils;
import com.runshu.newsmartark.entity.InventoryListEntity;
import com.runshu.newsmartark.mvp.contract.ProductTypeDtaContract;
import com.runshu.newsmartark.mvp.contract.ProductsByCategoryContract;
import com.runshu.newsmartark.mvp.model.ProductTypeDtaModel;
import com.runshu.newsmartark.mvp.model.ProductsByCategoryModel;
import com.runshu.newsmartark.mvp.presenter.ProductTypeDtaPresenter;
import com.runshu.newsmartark.mvp.presenter.ProductsByCategoryPresenter;
import com.runshu.newsmartark.network.netbean.HttpExecutor;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.RecyclerViewNoBugLinearLayoutManager;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.widget.TopTitleBar;
import com.zxl.library.DropDownMenu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Demo class
 *
 * @author yu
 * @date 2020/11/4
 * @decs：
 */

public class NewProDtaActivity extends BaseActivity implements ProductTypeDtaContract.View, ProductsByCategoryContract.View {
    @BindView(R.id.toolbar)
    TopTitleBar mToolbar;
    @BindView(R.id.tv_pro_name)
    TextView mTvProName;
    @BindView(R.id.dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.tv_all_num)
    TextView mTvAllNum;
    @BindView(R.id.rela_root)
    RelativeLayout mRelaRoot;
    private SwipeRefreshLayout swipe_layout;
    private RecyclerView recyclerView;
//    private String headers[] = {"产品库位", "产品类别", "生产厂家", "近效期"};
    private String headers[] = {"产品库位"};
    private String selectTypeOne[] = {};
    private String selectTypeTwo[] = {};
    private String selectTypeThree[] = {};
    private String selectTypeFour[] = {"全部", "近1个月", "近3个月", "近半年", "半年以上"};
    private ProductTypeDtaPresenter typeDtaPresenter;
    private ProductsByCategoryPresenter productsPresenter;
    private View contentView;
//    private int[] types = new int[]{DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY};
    private int[] types = new int[]{DropDownMenu.TYPE_LIST_CITY};
    private String mac;
//    private List<ProductsBean> mData;
    private List<InventoryListEntity.ListBean> mData;
//    private TakeStockAdapter mAdapter;
    private NewProDtaAdapter mAdapter;
    private int pageSize = 20;
    private int pageNum = 1;
    private boolean loading = true;
    private boolean isLoadMore = false;
    private List<CategoryListEntity> categoryList;
    private List<CategoryListEntity> StockSelList;
    private List<CategoryListEntity> ManufacturerSelList;
    private String categoryValue, stockName, model, manufacturer;
    private int stockNameID, expiryDate;

    @Override
    protected int getLayoutId() {
        return R.layout.act_new_prodta;
    }

    @Override
    protected void initView() {
        categoryList = new ArrayList<>();
        StockSelList = new ArrayList<>();
        ManufacturerSelList = new ArrayList<>();
        mac = MacUtils.getFormatMacAddr();
        mToolbar.setIsShowBac(true);
        mToolbar.setTitle("库存明细");
        contentView = getLayoutInflater().inflate(R.layout.content_allpro_dta, null);
        swipe_layout = contentView.findViewById(R.id.swipe_layout);
        recyclerView = contentView.findViewById(R.id.recy_all_pro);
        typeDtaPresenter = new ProductTypeDtaPresenter(this, new ProductTypeDtaModel());
        productsPresenter = new ProductsByCategoryPresenter(this, new ProductsByCategoryModel());
    }

    @Override
    protected void initData() {
//        typeDtaPresenter.getCategoryList(mac, 0);
        typeDtaPresenter.getStockType(HwInfoUtils.getCustomerId(context),HwInfoUtils.getHospitalId(context));
        mAdapter = new NewProDtaAdapter(mData);
        recyclerView.setLayoutManager(new RecyclerViewNoBugLinearLayoutManager(context));
        recyclerView.setAdapter(mAdapter);
        mAdapter.bindToRecyclerView(recyclerView);
        mAdapter.setEmptyView(R.layout.empty_view);

    }


    @Override
    public void onResume() {
        super.onResume();
        mDropDownMenu.setFocusableInTouchMode(true);
        mDropDownMenu.requestFocus();
        mDropDownMenu.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                //退出activity前关闭菜单
                if (mDropDownMenu.isShowing()) {
                    mDropDownMenu.closeMenu();
                    return true;
                } else {
                    return false;
                }
            }
            return false;
        });


    }



    /**
     * 设置类型和数据源：
     * DropDownMenu.KEY对应类型（DropDownMenu中的常量，参考上述核心源码）
     * DropDownMenu.VALUE对应数据源：key不是TYPE_CUSTOM则传递string[],key是TYPE_CUSTOM类型则传递对应view
     */
    private List<HashMap<String, Object>> initViewData() {
        List<HashMap<String, Object>> viewDatas = new ArrayList<>();
        HashMap<String, Object> map;
        for (int i = 0; i < headers.length; i++) {
            map = new HashMap<String, Object>();
            map.put(DropDownMenu.KEY, types[i]);
            if (i == 0) {
                map.put(DropDownMenu.VALUE, selectTypeOne);
//                map.put(DropDownMenu.SELECT_POSITION, 1);
            } else if (i == 1) {
                map.put(DropDownMenu.VALUE, selectTypeTwo);
//                map.put(DropDownMenu.SELECT_POSITION, 0);
            } else if (i == 2) {
                map.put(DropDownMenu.VALUE, selectTypeThree);
//                map.put(DropDownMenu.SELECT_POSITION,2);
            } else {
                map.put(DropDownMenu.VALUE, selectTypeFour);
            }
            viewDatas.add(map);
        }
        return viewDatas;
    }

    @Override
    protected void bindListener() {
        //该监听回调只监听默认类型，如果是自定义view请自行设置，参照demo
        mDropDownMenu.addMenuSelectListener((index, pos, clickstr) -> {
            //index:点击的tab索引，pos：单项菜单中点击的位置索引，clickstr：点击位置的字符串
            LogUtil.e(TAG, "===index==" + index + "pos====" + pos);
            if (index == 0) {
                stockName = StockSelList.get(pos).getValue();
                stockNameID = pos;
                if (pos == 0) {
                    mDropDownMenu.setTabText(0, "产品库位");
                }
            } else if (index == 1) {
                categoryValue = categoryList.get(pos).getValue();
                if (pos == 0) {
                    mDropDownMenu.setTabText(1, "产品类别");
                }
            } else if (index == 2) {
                manufacturer = ManufacturerSelList.get(pos).getValue();
                if (pos == 0) {
                    mDropDownMenu.setTabText(2, "生产厂家");
                }
            } else {
                expiryDate = pos;
                if (pos == 0) {
                    mDropDownMenu.setTabText(3, "近效期");
                }
            }
            //网络请求
            loading = false;
            isLoadMore = false;
            pageNum = 1;//设为默认加载第一页
            mData.clear();
            productsPresenter.getInventoryList(HwInfoUtils.getCustomerId(context),HwInfoUtils.getHospitalId(context),stockName, pageSize, pageNum);
//            productsPresenter.getProDta(mac, categoryValue, stockName, model, manufacturer, expiryDate, 0, pageSize, pageNum);
        });


        swipe_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loading = false;
                isLoadMore = false;
                pageNum = 1;//设为默认加载第一页
                mData.clear();
                productsPresenter.getInventoryList(HwInfoUtils.getCustomerId(context),HwInfoUtils.getHospitalId(context),stockName, pageSize, pageNum);

//                productsPresenter.getProDta(mac, categoryValue, stockName, model, manufacturer, expiryDate, 0, pageSize, pageNum);
            }
        });

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loading = false;
                isLoadMore = true;
                productsPresenter.getInventoryList(HwInfoUtils.getCustomerId(context),HwInfoUtils.getHospitalId(context),stockName, pageSize, pageNum);

//                productsPresenter.getProDta(mac, categoryValue, stockName, model, manufacturer, expiryDate, 0, pageSize, pageNum);
            }
        });
        swipe_layout.setRefreshing(true);
        swipe_layout.post(() -> {
            productsPresenter.getInventoryList(HwInfoUtils.getCustomerId(context),HwInfoUtils.getHospitalId(context),stockName, pageSize, pageNum);

//            productsPresenter.getProDta(mac, categoryValue, stockName, model, manufacturer, expiryDate, 0, pageSize, pageNum);
        });

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                isLoadMore = true;
                productsPresenter.getInventoryList(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context), stockName, pageSize, pageNum);
//                productsPresenter.getProDta(mac, categoryValue, stockName, model, manufacturer, expiryDate, 0, pageSize, pageNum);
            }
        });

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(context, ProDetailActivity.class);
//                intent.putExtra("manufacturer", mAdapter.getData().get(position).getProductVendor());
//                intent.putExtra("productNo", mAdapter.getData().get(position).getProductNo());
                intent.putExtra("model", mAdapter.getData().get(position).getGoodsModel());
                intent.putExtra("stockNameID", stockNameID);
                intent.putExtra("stockName", stockName);
//                intent.putExtra("expiryDate", expiryDate);
                intent.putExtra("productName", mAdapter.getData().get(position).getGoodsName());
                intent.putExtra("goodsId", mAdapter.getData().get(position).getGoodsId());
                startActivity(intent);
            }
        });

    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {

    }


    @Override
    public void onGetCategoryListSuccess(ResponseBean responseBean) {
        categoryList = (List<CategoryListEntity>) responseBean.pullData();
        if (categoryList == null)
            return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : categoryList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeTwo = strings.toArray(new String[strings.size()]);
        typeDtaPresenter.getStockSel(mac, 0);
    }

    @Override
    public void onGetStockSelSuccess(ResponseBean responseBean) {
        StockSelList = (List<CategoryListEntity>) responseBean.pullData();
        if (StockSelList == null) return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : StockSelList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeOne = strings.toArray(new String[strings.size()]);
        typeDtaPresenter.getManufacturerSel(mac, 0);
    }

    @Override
    public void onManufacturerSelSuccess(ResponseBean responseBean) {
        if (NewProDtaActivity.this.isFinishing() || mDropDownMenu == null) return;
        ManufacturerSelList = (List<CategoryListEntity>) responseBean.pullData();
        if (ManufacturerSelList == null)
            return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : ManufacturerSelList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeThree = strings.toArray(new String[strings.size()]);
        if (mDropDownMenu != null)
            mDropDownMenu.setDropDownMenu(Arrays.asList(headers), initViewData(), contentView);
    }

    @Override
    public void onModelSelSuccess(ResponseBean responseBean) {



    }

    @Override
    public void onGetStockTypeSuccess(ResponseBean responseBean) {
        StockSelList = (List<CategoryListEntity>) responseBean.pullData();
        if (StockSelList == null) return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : StockSelList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeOne = strings.toArray(new String[strings.size()]);
        if (mDropDownMenu != null)
            mDropDownMenu.setDropDownMenu(Arrays.asList(headers), initViewData(), contentView);
    }

    @Override
    public void onGetProDtaSuccess(ResponseBean responseBean) {
//        swipe_layout.setRefreshing(false);//完成刷新
//        NewTakeStockEntity stockEntity = (NewTakeStockEntity) responseBean.pullData();
//        mData = stockEntity.getList();
//        if (mTvAllNum != null)
//            mTvAllNum.setText(stockEntity.getStock());
//        if (isLoadMore) {
//            mAdapter.loadMoreComplete();//网络请求成功的话调用loadMoreComplete()
//        }
//        if (mData != null && mData.size() > 0) {//有了请求数据
//            if (isLoadMore) {//为true时，是加载更多获取的数据
//                mAdapter.addData(mData);//加载更多的数据，add进去
//            } else {
//                mAdapter.setNewData(mData);//进入或者上拉加载的数据(page=1),setnewdata
//            }
//            if (mData.size() == pageSize) {//获取的数据未10条时，说明还有下一页，page加1，以备下次请求
//                pageNum++;
//                mAdapter.setEnableLoadMore(true);//允许加载更多
//            } else {
//                mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
//            }
//
//        } else {
//            if (pageNum == 1) {
//                //数据得清空才会显示空布局
//                mAdapter.getData().clear();
//                mAdapter.notifyDataSetChanged();
//            }
//            mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
//        }
    }

    @Override
    public void onGetInventoryListSuccess(ResponseBean responseBean) {
        swipe_layout.setRefreshing(false);//完成刷新
        InventoryListEntity stockEntity = (InventoryListEntity) responseBean.pullData();
        mData = stockEntity.getList();
        if (mTvAllNum != null)
            mTvAllNum.setText(String.valueOf(stockEntity.getTotal()));
        if (isLoadMore) {
            mAdapter.loadMoreComplete();//网络请求成功的话调用loadMoreComplete()
        }
        if (mData != null && mData.size() > 0) {//有了请求数据
            if (isLoadMore) {//为true时，是加载更多获取的数据
                mAdapter.addData(mData);//加载更多的数据，add进去
            } else {
                mAdapter.setNewData(mData);//进入或者上拉加载的数据(page=1),setnewdata
            }
            if (mData.size() == pageSize) {//获取的数据未10条时，说明还有下一页，page加1，以备下次请求
                pageNum++;
                mAdapter.setEnableLoadMore(true);//允许加载更多
            } else {
                mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
            }

        } else {
            if (pageNum == 1) {
                //数据得清空才会显示空布局
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
            }
            mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
        }
    }

    @Override
    public void onError(String msg) {
        if (isLoadMore) {
            mAdapter.loadMoreFail();//请求失败的话调用loadMoreFail()
        }
        ToastUtils.showText(msg);
    }


    @OnClick(R.id.tv_pro_name)
    public void onViewClicked() {
        Intent intent = new Intent(this, SearchDtaActivity.class);
        startActivity(intent);
    }

    @Override
    public void onScanSuccess(String barcode) {
        super.onScanSuccess(barcode);
        scanToOpenDoor(barcode, true);
    }

    @Override
    protected void onDestroy() {
        HttpExecutor.cancleRequest(ConstantUrl.GET_deliveryTitie);
        super.onDestroy();
    }
}